import React, { useEffect, useState } from "react";
import style from "./index.module.scss";
import CourseList from "../CourseList";
import { Modal, message } from "antd";
import { delCourse, delVideo, getCourse, getVideo, updateVideo } from "@/api";
import CourseModal from "../CourseModal";
type TCourseMenu = {
  isOpen: boolean;
  onOk?: () => void;
  onCancel?: () => void;
  subjectId?: number;
  wrapperClassName?: string;
};
export default function CourseMenu(props: TCourseMenu) {
  const { isOpen, onOk, onCancel, subjectId, wrapperClassName } = props;
  const [courseId, setCourseId] = useState(0);
  const [corseList, setCourseList] = useState([]);
  const [isEditeOpen, setIsEditeOpen] = useState(false);
  const [courseName, setCourseName] = useState("");
  const [videoUrl, setVideoUrl] = useState("");
  const getCourseList = async () => {
    const res = await getCourse({
      pageNum: 1,
      pageSize: 1000,
      subjectId: subjectId,
    });
    setCourseList(res.data.data.records);
  };
  const delCourses = async (id: number) => {
    const res = await delCourse([id]);
    if (res.data.code === 200) {
      message.success("删除成功");
      getCourseList();
    }
  };
  const editeCourse = (sId: number) => {
    setCourseId(sId);
    setIsEditeOpen(true);
  };
  const onCanCel = () => {
    setIsEditeOpen(false);
    setCourseName("");
    setVideoUrl("");
  };
  const onReqiure = async () => {
    const res = await updateVideo({
      id: courseId,
      videoName: courseName,
      videoLink: videoUrl,
    });
    if (res.data.code === 200) {
      message.success("编辑成功");
      setIsEditeOpen(false);
      setCourseName("");
      setVideoUrl("");
      getCourseList();
    }
  };
  const memoCourseList = React.useMemo(() => corseList, [corseList]);
  useEffect(() => {
    isOpen && getCourseList();
  }, [isOpen]);
  return (
    <div>
      <Modal open={isOpen} onOk={onOk} onCancel={onCancel} footer={null}>
        <CourseList
          wrapperClassName={style["courseMenuWrapper"]}
          isShowOpration={true}
          coursesData={memoCourseList}
          delCourse={delCourses}
          editeCourse={editeCourse}
        ></CourseList>
      </Modal>
      <CourseModal
        open={isEditeOpen}
        onOk={onReqiure}
        onCancel={onCanCel}
        courseName={courseName}
        setCourseName={setCourseName}
        videoUrl={videoUrl}
        setVedioUrl={setVideoUrl}
        courseId={courseId}
      ></CourseModal>
    </div>
  );
}
